package org.stone.project.tx.handler.msgSendUserTypeHandler;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.stone.project.tx.config.CtxHolderProxy;
import org.stone.project.tx.handle.MsgSendUserTypeHandler;
import org.stone.project.tx.model.Message;
import org.stone.project.tx.pojo.dto.UuidUserCtxDto;
import org.stone.project.tx.prop.TxProp;
import org.stone.project.tx.sysEnum.MsgType;
import org.stone.project.tx.sysEnum.ReceiveType;
import org.stone.project.tx.utils.ResultUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 角色发送
 */
@Service
public class UserMsgSendGroupTypeHandler implements MsgSendUserTypeHandler {
    @Autowired
    private TxProp txProp;

    @Override
    public ReceiveType getReceiveType() {
        return ReceiveType.GROUP;
    }

    @Override
    public void sendMsg(Message msg) {
        List<String> allUserIdByRole = findAllUserIdByGroup(msg.getReceiveId());
        allUserIdByRole.parallelStream()
                .forEach(userId->{
                    Map<String, UuidUserCtxDto> receiveCtx = CtxHolderProxy.findByUserIdAll(userId);
                    MsgType msgType = MsgType.getInstance(msg.getContentType());
                    /**
                     * 只有在线或消息类别真确才会被发送
                     */
                    if (ObjectUtil.isNotNull(receiveCtx)  && ObjectUtil.isNotNull(msgType)){
                        receiveCtx.forEach((key,value)->{
                            value.getCtx().writeAndFlush(ResultUtil.ok(msgType,msg.getContent()));
                        });
                    }
                });
    }

    /**
     * todo 查询所有角色中所有用户
     * @return
     */
    private List<String> findAllUserIdByGroup(String roleId){
        return Arrays.asList("1","2","3","4","5");
    }
}
